#include "config.h"
#include "Arduino.h"

int sdState = 0;
int i2sState = 0;
char data[800];
const int offset = 0x2C;

void I2S_Init() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // 单声道设置
    .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .intr_alloc_flags = 0,
    .dma_buf_count = 16,
    .dma_buf_len = 60
  };

  i2s_pin_config_t pin_config = {
    .bck_io_num = PIN_I2S_BCLK,
    .ws_io_num = PIN_I2S_LRC,
    .data_out_num = PIN_I2S_DOUT,
    .data_in_num = -1  // Not used
  };

  i2s_driver_install((i2s_port_t)0, &i2s_config, 0, NULL);
  i2s_set_pin((i2s_port_t)0, &pin_config);
  i2s_set_clk((i2s_port_t)0, SAMPLE_RATE, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_MONO); // 设置单声道

  pinMode(PIN_I2S_SD, OUTPUT);
  i2sState = 1;
  digitalWrite(PIN_I2S_SD, LOW);
  sdState = LOW;
}


void I2S_Write(char* data, int numData) {
  if (sdState == LOW) {
    digitalWrite(PIN_I2S_SD, HIGH);
    sdState = HIGH;
  }
  i2s_port_t i2s_num = I2S_NUM_0;  // 或者 I2S_NUM_1，根据您的具体硬件配置
  size_t bytes_written;
  i2s_write(i2s_num, data, numData, &bytes_written, portMAX_DELAY);
}

void I2S_quite() {
  if (sdState == HIGH) {
    digitalWrite(PIN_I2S_SD, LOW);
    sdState = LOW;
  }
}

void I2S_play(String sound) {
  if (!SD.begin(SD_CS,MySPI)) {
    Serial.println("sd error");
  }
  File file = SD.open(sound);  // 44100Hz, 16bit, stereo, linear PCM
  file.seek(offset);
  if (i2sState == 0) {
    I2S_Init();
  }
  Serial.println("start play");
  while (file.readBytes(data, sizeof(data))) {
    I2S_Write(data, sizeof(data));
  }
  I2S_quite();
  file.close();
}

void I2S_play_file(File file){
  if(file){
    file.seek(offset);
    if (i2sState == 0) {
      I2S_Init();
    }
    Serial.println("start play");
    while (file.readBytes(data, sizeof(data))) {
      I2S_Write(data, sizeof(data));
    }
    I2S_quite();
    file.close();
  }
  else{
    Serial.println("I2S_play_file:file error");
  }
}

